#include "music.h"
#include <QUuid>
#include <QMediaPlayer>
#include <QCoreApplication>
#include <QSqlQuery>
#include <QSqlError>

Music::Music()
    :isLike(false),
     isHistory(false)
{
    // uuid
    musicId = QUuid::createUuid().toString();
}

Music::Music(const QUrl &url)
    :isLike(false),
     isHistory(false),
     musicUrl(url)
{
    musicId = QUuid::createUuid().toString();
    parseMediaMetaData();
}

void Music::setMusicName(const QString &musicName)
{
    this->musicName = musicName;
}
void Music::setSingerName(const QString &singerName)
{
    this->singerName = singerName;
}
void Music::setAlbumName(const QString &albumName)
{
    this->albumName = albumName;
}
void Music::setDuration(const qint64 duration)
{
    this->duration = duration;
}
void Music::setMusicId(const QString &musicId)
{
    this->musicId = musicId;
}
void Music::setMusicUrl(const QUrl &musicUrl)
{
    this->musicUrl = musicUrl;
}
void Music::setIsLike(bool isLike)
{
    this->isLike = isLike;
}
void Music::setIsHistory(bool isHistory)
{
    this->isHistory = isHistory;
}

QString Music::getMusicName() const
{
    return musicName;
}
QString Music::getSingerName() const
{
    return singerName;
}
QString Music::getAlbumName() const
{
    return albumName;
}
qint64 Music::getDuration() const
{
    return duration;
}
QString Music::getMusicId() const
{
    return musicId;
}
QUrl Music::getMusicUrl() const
{
    return musicUrl;
}
bool Music::getIsLike() const
{
    return isLike;
}
bool Music::getIsHistory() const
{
    return isHistory;
}

QString Music::getLrcFilePath() const
{
    QString path = musicUrl.toLocalFile();
    int pos = path.lastIndexOf('/');
    path.insert(pos + 1, "lrc/");
    path.replace(".mp3", ".lrc");
    path.replace(".flac", ".lrc");
    path.replace(".mpga", ".lrc");
    qDebug() << "歌词路径" << path;
    return path;
}

void Music::insertMusicToDB()
{
    // 检测数据是否存在
    QSqlQuery query;
    // select 1... 只需要知道存不存在, 返回1是效率最高的
    // select exists(子查询) 如果有记录, 返回true, 没有, false
    query.prepare("select exists(select 1 from musicInfo where musicId = ?)");
    query.addBindValue(musicId);
    if (!query.exec())
    {
        qDebug() << "查询失败:" << query.lastError().text();
    }

    if (query.next())
    {
        bool isExists = query.value(0).toBool();
        if (isExists)
        {
            // 存在, 更新
            qDebug() << "存在";
            query.prepare("update musicInfo set isLike = ?, isHistory = ? where musicId = ?");
            query.addBindValue(isLike? 1 : 0);
            query.addBindValue(isHistory? 1 : 0);
            query.addBindValue(musicId);
            if (!query.exec())
            {
                qDebug()<<"更新失败: "<<query.lastError().text();
            }

            qDebug()<<"更新music信息: "<<musicName<<" "<<musicId;
        }
        else
        {
            // 不存在, 插入
            qDebug() << "不存在";
            query.prepare("insert into musicInfo(musicId, musicName, musicSinger, musicAlbum, \
                                                 duration, musicUrl, isLike, isHistory) values\
                                                 (?,?,?,?,?,?,?,?)");

            query.addBindValue(musicId);
            query.addBindValue(musicName);
            query.addBindValue(singerName);
            query.addBindValue(albumName);
            query.addBindValue(duration);
            query.addBindValue(musicUrl.toLocalFile());
            query.addBindValue(isLike ? 1 : 0);
            query.addBindValue(isHistory? 1 : 0);

            if (!query.exec())
            {
                qDebug()<<"插入失败: "<<query.lastError().text();
                return;
            }

            qDebug()<<"插入music信息: "<<musicName<<" "<<musicId;
        }
    }

}

void Music::parseMediaMetaData()
{
    QMediaPlayer player;
    // 设置媒体源
    player.setMedia(musicUrl);
    // 原数据解析需要时间，解析完毕才能提取，需要循环
    // 循环时消息循环可以继续，processEvent
    while (!player.isMetaDataAvailable())
    {
        QCoreApplication::processEvents();
    }

    if (player.isMetaDataAvailable())
    {
        // 提取数据
        musicName = player.metaData("Title").toString();
        singerName = player.metaData("Author").toString();
        albumName = player.metaData("AlbumTitle").toString();
        duration = player.duration();

        if (musicName.isEmpty())
        {
            QString fileName = musicUrl.fileName();
            // 歌曲-歌手.mp3  歌曲名.mp3
            // 找-的位置
            int index = fileName.indexOf('-');
            if (index != -1)
            {
                musicName = fileName.mid(0, index).trimmed();
            }
            else
            {
                musicName = fileName.mid(0, fileName.indexOf('.')).trimmed();
            }

            if (musicName.isEmpty())
            {
                musicName = musicUrl.toString();
            }

            // 歌手为空
            if (singerName.isEmpty())
            {
                if (index != -1)
                {
                    singerName = fileName.mid(index + 1, fileName.indexOf('.') - index - 1).trimmed();
                }
                else

                {
                    singerName = "未知歌手";
                }
            }
        }

        if (albumName.isEmpty())
        {
            albumName = "未知专辑";
        }

        qDebug()<<musicName<<" "<<singerName<<" "<<albumName<<" "<<duration;
    }
}
